<?php
/**
 *
 * Author: Lyu
 * Date: 2023/8/8
 * Time: 10:05
 */

namespace App\OpenApi\AdminApi\Common;

use App\Library\Service\ExportService;
use App\Model\Core\Admin\AdminFileModel;
use App\Service\Core\Admin\File\AdminExportFileApplyService;
use App\Service\Core\Admin\File\AdminFileListService;
use App\Service\Core\Admin\File\AdminFileService;
use App\Service\OpenApi\AdminApi\OpenBaseApi;

class ExportFileApi extends OpenBaseApi
{

    public function index(): array
    {
        $list = (new AdminFileListService())
            ->setFields(['*', 'file_type_name', 'operate_type_name', 'status_name', 'download'])
            ->setPage($this->input('page'), $this->input('page_size'))
            ->setOperateType(AdminFileModel::OPERATE_EXPORT)
            ->setCreatedAt($this->input('start_at'), $this->input('end_at'))
            ->setStatus($this->input('status'))
            ->setFileType($this->input('file_type'))
            ->setRemark($this->input('remark'))
            ->getList();
        $data = $list;
        $data['file_type_list'] = AdminFileModel::$export_type;
        $data['operate_type_list'] = AdminFileModel::$operate_type;
        $data['status_list'] = AdminFileModel::$status;
        return alert_info(0, 'ok', $data);
    }

    /**
     * 获取导出字段
     * @return array
     */
    public function show(): array
    {
        $service = $this->input('exportService');
        try {
            $service = base64_decode($service);
            $exportService = new $service();
            return alert_info(0, 'ok', [
                'allow_export_fields' => $exportService::$allow_export_fields,
                'default_export_fields' => $exportService::$default_export_fields,
            ]);
        } catch (\Error $error) {
            return alert_info(1, $error->getMessage());
        }
    }

    /**
     * 导出请求
     * @return array
     */
    public function export(): array
    {
        $data = $this->request;
        $Service = base64_decode($data['exportService']);
        $return_url = base64_decode($data['return_url']);
        $remark = $data['remark'];
        unset($data['remark'], $data['service'], $data['return_url']);
        $ExportFileService = new AdminExportFileApplyService();
        $file_type = call_user_func([new $Service(), 'getFileType']);
        $data['this'] = get_object_vars($this);
        $data['session'] = \Session::all();
        $total = (int)$data['total'];
        if ($total > 0 && $total <= 100) {
            //数据量较少时候使用同步下载
            $res = call_user_func([new $Service(), 'syncExport'], $data);
            if ($res['code'] !== 0) {
                return $res;
            } else {
                $data = [
                    'is_download' => 1,
                    'jump_url' => easy_url('/download', ['file' => ExportService::encryptFilePath(easy_attached_path($res['data']['file_path']))])
                ];
                return alert_info(0, '导出成功', $data);
            }
        } else {
            $res = $ExportFileService->setRemark($remark)
                ->setHandle($Service)
                ->setRequest($data)
                ->setExportType($file_type)
                ->setOperate($this->operate_id, $this->operate_by)
                ->apply();
            $res['data']['jump_url'] = $return_url;
            $res['data']['is_download'] = 0;
            return $res;
        }
    }

    /**
     * 下载文件
     */
    public function download()
    {
        $file_id = $this->input('file_id');
        if (!is_numeric($file_id) || $file_id <= 0) {
            return alert_info(1, '参数错误');
        }
        $CoreFileService = AdminFileService::getInstance();
        $file_info = $CoreFileService->getOne($file_id);
        if (empty($file_info)) {
            return alert_info(1, '记录不存在');
        }
        $res = $CoreFileService->download($file_id);
        if ($res['code'] !== 0) {
            return $res;
        }
        $data = [
            'is_download' => 1,
            'jump_url' => easy_url('/download', ['file' => ExportService::encryptFilePath(easy_attached_path($res['data']['file_path']))])
        ];
        return alert_info(0, '导出成功', $data);
    }
}
